package tree.test297;

import listbyorder.utils.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/7/17 13:03
 */
public class Solution1 {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if(root == null) return "#,";
        String res = root.val + ",";
        res += serialize(root.left);
        res += serialize(root.right);
        return res;
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        // 反序列化二叉树
        String[] strs = data.split(",");
        Queue<String> q = new LinkedList<>();
        for(String s : strs){
            q.add(s);
        }
        return dfs(q);
    }

    private TreeNode dfs(Queue<String> q){
        String s = q.poll();
        if(s.equals("#")) return null;
        TreeNode root = new TreeNode(Integer.parseInt(s));
        root.left = dfs(q);
        root.right = dfs(q);
        return root;
    }

}
